﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.Lite;
using DICE_GS;

public class DeckEditSceneManager : LTEventListenerC {

	private static Queue<Dictionary<byte, object>> packetQueue = new Queue<Dictionary<byte, object>>();
	
	public UILabel[] teamRankLebel;
	public UILabel teamHPLabel;
	
    public GameObject[] teamSkillObject;
    public GameObject[] teamSkillBlankObject;
	public UISprite[] teamSkillIcon;
    public UILabel[] teamSkillName;
    public UILabel[] teamSkillDesc;
    public UILabel[] teamSkillMana;
	
	public UILabel teamCostLabel;
	
	public UISprite[] deckIndexButtonImages;
	
	public GameObject[] unitEvolutionButtons;
	
	public UILabel[] NameLabels;
	
	public MyUnitCard[] unitCardObjects;
	public GameObject[] blankCardObjects;
	
	public GameObject skillListWindow;
	
	int DeckUnitTotalHP = 0;
	
	public static int selectedDeckIndex;
	public UILabel selectedDeckIndexLabel;
	
	
	public static DeckEditSceneManager manager;
	
	public UISprite teamRankImage;
	
	public GameObject tabBackgroundImage;
	
	public static bool isFromGameReadyScene = false;

    public GameObject deckEditSceneObject;
    public GameObject unitSelectSceneObject;

    public GameObject currentTapPoint;

	Dictionary<int, DeckInfo> tempDeckMap = null;

	void Awake()
	{
		manager = this;
	}
	
	void Start()
	{
		tempDeckMap = new Dictionary<int, DeckInfo>(MyInfo.Instance.MyDeckMap);
		for(int i=0; i<MyInfo.Instance.MyDeckMap.Count; i++)
		{
			tempDeckMap[i] = new DeckInfo(MyInfo.Instance.MyDeckMap[i]);
		}
		_oldDeckIndex = MyInfo.Instance.MyCurrentDeck;

		int totalgrade = 0, totalCost = 0;
		SetCurrentDeckIndex();
		
		DeckInfo currentDeckInfo = MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck];

        Debug.LogError(currentDeckInfo.deckId);
		
		for(int i=0; i<currentDeckInfo.SlotMap.Count; i++)
		{
			if(currentDeckInfo.SlotMap[i].UnitDBID != 0 )
			{
				unitCardObjects[i].SetCardInfo(i, currentDeckInfo.SlotMap[i]);
				unitCardObjects[i].gameObject.SetActive(true);
				unitCardObjects[i].editSceneManager = this;
				blankCardObjects[i].gameObject.SetActive(false);
//				unitEvolutionButtons[i].gameObject.SetActive(true);
				DeckUnitTotalHP += currentDeckInfo.SlotMap[i].hp;
				CUnitData unitData = CUnitDataManager.Instance.GetUnitData(currentDeckInfo.SlotMap[i].UnitClassID);
				totalgrade += unitData.grade;
                totalCost += unitData.unit_cost;
			}
			else
			{
                unitCardObjects[i].index = i;
				unitCardObjects[i].gameObject.SetActive(false);
				blankCardObjects[i].gameObject.SetActive(true);
				unitCardObjects[i].editSceneManager = this;	
//				unitEvolutionButtons[i].gameObject.SetActive(false);
			}
		}
		
		teamHPLabel.text = DeckUnitTotalHP.ToString();

        if (currentDeckInfo.skill1_IconName == null)
            teamSkillBlankObject[0].SetActive(true);
        else
        {
            teamSkillObject[0].SetActive(true);
            teamSkillIcon[0].spriteName = currentDeckInfo.skill1_IconName;
            teamSkillName[0].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill1Data.name_string);
            teamSkillDesc[0].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill1Data.desc_string);
            teamSkillMana[0].text = "MP " + currentDeckInfo.skill1Data.cost;
        }

        if (currentDeckInfo.skill2_IconName == null)
            teamSkillBlankObject[1].SetActive(true);
        else
        {
            teamSkillObject[1].SetActive(true);
            teamSkillIcon[1].spriteName = currentDeckInfo.skill2_IconName;
            teamSkillName[1].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill2Data.name_string);
            teamSkillDesc[1].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill2Data.desc_string);
            teamSkillMana[1].text = "MP " + currentDeckInfo.skill2Data.cost;
        }
		
		if( totalgrade / 5 >= 5 )
			teamRankImage.spriteName = "ScoreA_SS";
		else if( (totalgrade / 5) < 5 && (totalgrade / 5) >= 4 )
			teamRankImage.spriteName = "ScoreA_S";
		else if( (totalgrade / 5) < 4 && (totalgrade / 5) >= 3 )
			teamRankImage.spriteName = "ScoreA_A";
		else if( (totalgrade / 5) < 3 && (totalgrade / 5) >= 2 )
			teamRankImage.spriteName = "ScoreA_B";
		else if( (totalgrade / 5) < 2 && (totalgrade / 5) >= 1 )
			teamRankImage.spriteName = "ScoreA_C";
		else
			teamRankImage.spriteName = "ScoreA_D";

        teamCostLabel.text = "("+totalCost+"/"+MyInfo.Instance.maxUnitCost+")";
	
		for(int i=0; i<5; i++)
		{
			if( MyInfo.Instance.MyDeckMap.ContainsKey(i) )
			{
                if (i == MyInfo.Instance.MyCurrentDeck)
                {
                    deckIndexButtonImages[i].spriteName = "FormATeam_Tam01";
                    deckIndexButtonImages[i].transform.parent.FindChild("Label").GetComponent<UILabel>().color = new Color(196f / 255f, 179f / 255f, 88f / 255f);
                    currentTapPoint.transform.parent = deckIndexButtonImages[i].transform;
                    currentTapPoint.transform.localPosition = new Vector3(43f, 13f, 0f);
                    currentTapPoint.transform.localScale = Vector3.one;
                }
                else
                {
                    deckIndexButtonImages[i].spriteName = "FormATeam_Tam02";
                    deckIndexButtonImages[i].transform.parent.FindChild("Label").GetComponent<UILabel>().color = new Color(88f / 255f, 76f / 255f, 45f / 255f);
                }

			}
			else
			{
				deckIndexButtonImages[i].transform.parent.gameObject.SetActive(false);
			}
		}
		
		LoadingWindow.window.HideLoading();
	}
	
	void RefreshCardinfos()
	{
        int totalgrade = 0, totalCost = 0;
		DeckUnitTotalHP = 0;
		SetCurrentDeckIndex();
		
		DeckInfo currentDeckInfo = MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck];
		
		for(int i=0; i<currentDeckInfo.SlotMap.Count; i++)
		{
			if(currentDeckInfo.SlotMap[i].UnitDBID != 0 )
			{
                Debug.LogError(currentDeckInfo.SlotMap[i].UnitDBID);
				unitCardObjects[i].SetCardInfo(i, currentDeckInfo.SlotMap[i]);
				unitCardObjects[i].gameObject.SetActive(true);
//				teamCardObjects[i].editManager = this;
				blankCardObjects[i].gameObject.SetActive(false);
//				unitEvolutionButtons[i].gameObject.SetActive(true);
				DeckUnitTotalHP += currentDeckInfo.SlotMap[i].hp;
				CUnitData unitData = CUnitDataManager.Instance.GetUnitData(currentDeckInfo.SlotMap[i].UnitClassID);
				totalgrade += unitData.grade;
                totalCost += unitData.unit_cost;
			}
			else
			{
				unitCardObjects[i].gameObject.SetActive(false);
				blankCardObjects[i].gameObject.SetActive(true);
//				blankCardObjects[i].editManager = this;
//				unitEvolutionButtons[i].gameObject.SetActive(false);
			}
		}
		
		teamHPLabel.text = DeckUnitTotalHP.ToString();

        if (currentDeckInfo.skill1_IconName == null)
        {
            teamSkillObject[0].SetActive(false);
            teamSkillBlankObject[0].SetActive(true);
        }
        else
        {
            teamSkillBlankObject[0].SetActive(false);
            teamSkillObject[0].SetActive(true);
            teamSkillIcon[0].spriteName = currentDeckInfo.skill1_IconName;
            teamSkillName[0].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill1Data.name_string);
            teamSkillDesc[0].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill1Data.desc_string);
            teamSkillMana[0].text = "MP " + currentDeckInfo.skill1Data.cost;
        }

        if (currentDeckInfo.skill2_IconName == null)
        {
            teamSkillObject[1].SetActive(false);
            teamSkillBlankObject[1].SetActive(true);
        }
        else
        {
            teamSkillBlankObject[1].SetActive(false);
            teamSkillObject[1].SetActive(true);
            teamSkillIcon[1].spriteName = currentDeckInfo.skill2_IconName;
            teamSkillName[1].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill2Data.name_string);
            teamSkillDesc[1].text = CStringTableManager.Instance.GetItemByName(currentDeckInfo.skill2Data.desc_string);
            teamSkillMana[1].text = "MP " + currentDeckInfo.skill2Data.cost;
        }
		
		if( currentDeckInfo.currentActivateCardCount != 0 )
		{
			if( totalgrade / 5 >= 5 )
				teamRankImage.spriteName = "ScoreA_SS";
			else if( (totalgrade / 5) < 5 && (totalgrade / 5) >= 4 )
				teamRankImage.spriteName = "ScoreA_S";
			else if( (totalgrade / 5) < 4 && (totalgrade / 5) >= 3 )
				teamRankImage.spriteName = "ScoreA_A";
			else if( (totalgrade / 5) < 3 && (totalgrade / 5) >= 2 )
				teamRankImage.spriteName = "ScoreA_B";
			else if( (totalgrade / 5) < 2 && (totalgrade / 5) >= 1 )
				teamRankImage.spriteName = "ScoreA_C";
			else
				teamRankImage.spriteName = "ScoreA_D";
		}
		else
		{
            teamRankImage.spriteName = "ScoreA_D";
		}

        teamCostLabel.text = "(" + totalCost + "/45)";
		
        //for(int i=0; i<5; i++)
        //{
        //    unitCardObjects[i].selectButtonObject.SetActive(false);
        //    unitCardObjects[i].takeOffButtonObject.SetActive(false);
        //}
	}

	// Update is called once per frame
	void Update()
	{
		while (packetQueue.Count > 0)
		{
			Dictionary<byte, object> tmpPacket = packetQueue.Dequeue();

			switch ((byte)tmpPacket[0])
			{
				default:
					glog.debug("DeckEditSceneManager's Packet Handler Unknown Packet Recieved [" + (byte)tmpPacket[0] + "]");
					break;
			}
		}
	}


	public static bool PacketHandler(Dictionary<byte, object> _packet)
	{
		glog.debug("DeckEditSceneManager Got Packet");
		if (packetQueue != null)
		{
			packetQueue.Enqueue(_packet);
			return true;
		}

		return false;
	}
	
	void SetCurrentDeckIndex()
	{
		for(int i=0; i<MyInfo.Instance.MyDeckMap.Count; i++)
		{
			if(i == MyInfo.Instance.MyCurrentDeck )
			{
                deckIndexButtonImages[i].spriteName = "FormATeam_Tam01";
                deckIndexButtonImages[i].transform.parent.FindChild("Label").GetComponent<UILabel>().color = new Color(196f / 255f, 179f / 255f, 88f / 255f);
                currentTapPoint.transform.parent = deckIndexButtonImages[i].transform;
                currentTapPoint.transform.localPosition = new Vector3(43f, 13f, 0f);
                currentTapPoint.transform.localScale = Vector3.one;
                //tabBackgroundImage.transform.parent = deckIndexButtonImages[i].transform;
                //tabBackgroundImage.transform.localPosition = new Vector3(-1f,-7f,0f);
                //tabBackgroundImage.transform.localScale = Vector3.one;
                //selectedDeckIndexLabel.text = CStringTableManager.Instance.GetItemById(1692).Replace("{DeckIndex}", (i+1).ToString());
			}
			else
			{
                deckIndexButtonImages[i].spriteName = "FormATeam_Tam02";
                deckIndexButtonImages[i].transform.parent.FindChild("Label").GetComponent<UILabel>().color = new Color(88f / 255f, 76f / 255f, 45f / 255f);
			}
		}
	}
	
	public void ClickedTeamCard()
	{
        deckEditSceneObject.SetActive(false);
        unitSelectSceneObject.SetActive(true);
	}

    public void OnClickedCardSelectFinishButton()
    {
        RefreshCardinfos();
        deckEditSceneObject.SetActive(true);
        unitSelectSceneObject.SetActive(false);
    }
	
	void ClickedFinishButton()
	{
		deckInfoSendingCount = 1;
		LoadingWindow.window.ShowShortLoading();
		MyInfo.Instance.MyDeckMap[_oldDeckIndex].order = 0;
		MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].order = 1;
		for(int i=0; i<MyInfo.Instance.MyDeckMap.Count; i++)
		{
			if( i != MyInfo.Instance.MyCurrentDeck )
				MyInfo.Instance.MyDeckMap[i].order = 0;
			
			RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallbak, MyInfo.Instance.MyDeckMap[i].deckId);
		}
	}
	
	int deckInfoSendingCount=1;
	void ReturnCallbak(Hashtable returnData)
	{
		switch((RestAPIProtocol)returnData["protocol"])
		{
		case RestAPIProtocol.SENDMYDECKCHANGEINFO:
			Debug.LogError(deckInfoSendingCount);
			if( deckInfoSendingCount++ >= MyInfo.Instance.MyDeckMap.Count )
			{
				if( !isFromGameReadyScene )
					CSceneManager.manager.GoToWaitroomScene();
				else
					CSceneManager.manager.GoToGameReadyScene();;
				LoadingWindow.window.HideLoading();
			}
			break;
		}
	}
	
	public void SetSkillIcon(int skillId, string iconName)
	{
        CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
        teamSkillBlankObject[selectedSkillIconIndex].SetActive(false);
        teamSkillObject[selectedSkillIconIndex].SetActive(true);
		teamSkillIcon[selectedSkillIconIndex].spriteName = iconName;
        if (skillData != null)
        {
            teamSkillName[selectedSkillIconIndex].text = CStringTableManager.Instance.GetItemByName(skillData.name_string);
            teamSkillDesc[selectedSkillIconIndex].text = CStringTableManager.Instance.GetItemByName(skillData.desc_string);
            teamSkillMana[selectedSkillIconIndex].text = "MP " + skillData.cost;
        }
		if(selectedSkillIconIndex == 0 )
			MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].skill1 = skillId;
		else
			MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].skill2 = skillId;
	}
	
	public int selectedSkillIconIndex = -1;
	public override void OnEvent (int eventID)
	{
		base.OnEvent (eventID);
		
		//input skill Window close Button
		if( eventID == 100 )
		{
			skillListWindow.SetActive(false);
			return;
		}
		
		//input deck Index Button
		if( eventID >= 200 && eventID < 300 )
		{
			_oldDeckIndex = MyInfo.Instance.MyCurrentDeck;
			MyInfo.Instance.MyCurrentDeck = eventID - 200;
			RefreshCardinfos();
			return;
		}
		
		//input select deckcard
        if (eventID >= 300 && eventID < 400)
        {
            selectedDeckIndex = eventID - 300;
            Debug.LogError(eventID);
            Debug.LogError(selectedDeckIndex);
			deckEditSceneObject.SetActive(false);
			unitSelectSceneObject.SetActive(true);
            return;
        }
        else if( eventID >= 400 && eventID < 500 )
		{
			selectedDeckIndex = eventID-400;
            DeSelectCard();
			return;
		}
		
		selectedSkillIconIndex = eventID;
		skillListWindow.SetActive(true); 
		
		SkillListManager listManager = skillListWindow.GetComponentInChildren<SkillListManager>();
		listManager.RefreshItemStatus();
	}
	
	int dragDirection;
	public bool isDragging = false;
	public void Drag(int index, Vector2 delta)
	{
		if( isDragging == false)
		{
			dragDirection = delta.x < 0 ? -1 : 1;
//			foreach(TeamCard card in teamCardObjects)
//			{
//				if( card.gameObject.activeSelf ) 
//				{
//					TweenRotation rotation = TweenRotation.Begin(card.gameObject, 0.2f, Quaternion.Euler(new Vector3(0f,0f,0f)));
//					EventDelegate.Add(rotation.onFinished, OnRotationFinished, true);
//				}
//			}
			OnRotationFinished();
		}
		isDragging = true;
	}
	
	int _oldDeckIndex = 0;
	public int oldDeckIndex
	{
		get
		{
			return _oldDeckIndex;
		}
	}
	
	void OnRotationFinished()
	{
		if( dragDirection < 0 )
		{
			MyInfo.Instance.MyCurrentDeck -= 1;
			if( MyInfo.Instance.MyCurrentDeck < 0 )
				MyInfo.Instance.MyCurrentDeck = MyInfo.Instance.MyDeckMap.Count-1;
			RefreshCardinfos();
		}
		else
		{
			MyInfo.Instance.MyCurrentDeck += 1;
			if( MyInfo.Instance.MyCurrentDeck > MyInfo.Instance.MyDeckMap.Count-1 )
				MyInfo.Instance.MyCurrentDeck = 0;
			RefreshCardinfos();
		}
	}
	
	public bool isChangedDeck
	{
		get
		{
			return _oldDeckIndex == MyInfo.Instance.MyCurrentDeck ? false : true;
		}
	}
	
	public void DeSelectCard()
	{
		MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].SlotMap[selectedDeckIndex] = new UnitInfo(0,0,0,0,0);
        //unitCardObjects[selectedDeckIndex].selectButtonObject.SetActive(false);
        //unitCardObjects[selectedDeckIndex].takeOffButtonObject.SetActive(false);
		unitCardObjects[selectedDeckIndex].gameObject.SetActive(false);
		blankCardObjects[selectedDeckIndex].SetActive(true);
		
		int totalGrade = 0, totalHP = 0, totalCost = 0;
		
		DeckInfo currentDeckInfo = MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck];
		for(int i=0; i<currentDeckInfo.SlotMap.Count; i++)
		{
			if(currentDeckInfo.SlotMap[i].UnitDBID != 0 )
			{
				CUnitData unitData = CUnitDataManager.Instance.GetUnitData(currentDeckInfo.SlotMap[i].UnitClassID);
				totalGrade += unitData.grade;
				totalHP += currentDeckInfo.SlotMap[i].hp;
                totalCost += unitData.unit_cost;
			}
		}
		
		teamHPLabel.text = totalHP.ToString();
		
		if( currentDeckInfo.currentActivateCardCount != 0 )
		{
			if( totalGrade / 5 >= 5 )
				teamRankImage.spriteName = "ScoreA_SS";
			else if( (totalGrade / 5) < 5 && (totalGrade / 5) >= 4 )
				teamRankImage.spriteName = "ScoreA_S";
			else if( (totalGrade / 5) < 4 && (totalGrade / 5) >= 3 )
				teamRankImage.spriteName = "ScoreA_A";
			else if( (totalGrade / 5) < 3 && (totalGrade / 5) >= 2 )
				teamRankImage.spriteName = "ScoreA_B";
			else if( (totalGrade / 5) < 2 && (totalGrade / 5) >= 1 )
				teamRankImage.spriteName = "ScoreA_C";
			else
				teamRankImage.spriteName = "ScoreA_D";
		}

        teamCostLabel.text = "(" + totalCost + "/45)";
	}
	
	public void DeActiveCardSelectButtons(int index)
	{
		for(int i=0; i<5; i++)
		{
			if( i != index)
			{
				unitCardObjects[i].selectButtonObject.SetActive(false);
				unitCardObjects[i].takeOffButtonObject.SetActive(false);
			}
		}
	}

    public void OnClickedBackButton()
    {
        if (CSceneManager.prevSceneIndex == SCENE.GameReadyScene)
        {
            CSceneManager.manager.GoToGameReadyScene();
        }
        else
        {
            CSceneManager.manager.GoToWaitroomScene();
        }

		MyInfo.Instance.MyDeckMap = new Dictionary<int, DeckInfo>(tempDeckMap);
    }
}
